// Copyright (c) 2014-2017 Bytter. All rights reserved.
// ============================================================================
// CURRENT VERSION
// ============================================================================
// CHANGE LOG
// V2.3 : 2017年5月3日, liuwl, creation
// ============================================================================
package com.betterjr.modules.commission.service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.betterjr.common.service.BaseService;
import com.betterjr.common.utils.BTAssert;
import com.betterjr.common.utils.BetterDateUtils;
import com.betterjr.common.utils.BetterStringUtils;
import com.betterjr.common.utils.Collections3;
import com.betterjr.common.utils.MathExtend;
import com.betterjr.common.utils.UserUtils;
import com.betterjr.mapper.pagehelper.Page;
import com.betterjr.modules.account.entity.CustOperatorInfo;
import com.betterjr.modules.commission.constant.CommissionPayResultStatus;
import com.betterjr.modules.commission.dao.CommissionPayResultMapper;
import com.betterjr.modules.commission.data.CalcPayResult;
import com.betterjr.modules.commission.entity.CommissionFile;
import com.betterjr.modules.commission.entity.CommissionFileDown;
import com.betterjr.modules.commission.entity.CommissionPayResult;
import com.betterjr.modules.commission.entity.CommissionPayResultRecord;
import com.betterjr.modules.commission.entity.CommissionRecord;
import com.betterjr.modules.customer.ICustMechBaseService;
import com.betterjr.modules.customer.entity.CustMechBase;

/**
 * @author liuwl
 *
 */
@Service
public class CommissionPayResultService extends BaseService<CommissionPayResultMapper, CommissionPayResult> {

    @Reference(interfaceClass = ICustMechBaseService.class)
    private ICustMechBaseService custMechBaseService;

    @Resource
    private CommissionFileService commissionFileService;

    @Resource
    private CommissionRecordService commissionRecordService;

    @Resource
    private CommissionDailyStatementService commissionDailyStatementService;

    @Resource
    private CommissionPayResultRecordService commissionPayResultRecordService;

    @Resource
    private CommissionFileDownService commissionFileDownService;

    @Resource
    private CommissionPayResultService commissionPayResultService;

    // 创建 日对账记录 所有日对账记录
    public CommissionPayResult saveCreatePayResult(final String anImportDate, final String anPayDate,
            final Long anCustNo) {
        BTAssert.isTrue(UserUtils.platformUser(), "操作失败！");

        BTAssert.isTrue(StringUtils.isNotBlank(anImportDate), "导入日期不允许为空！");
        BTAssert.isTrue(StringUtils.isNotBlank(anPayDate), "支付日期不允许为空！");

        final long importTime = BetterDateUtils.parseDate(BetterDateUtils.getNumDate()).getTime()
                - BetterDateUtils.parseDate(anImportDate).getTime();
        final long payTime = BetterDateUtils.parseDate(BetterDateUtils.getNumDate()).getTime()
                - BetterDateUtils.parseDate(anPayDate).getTime();

        BTAssert.isTrue(importTime >= 0, "导入日期必须小于等于当前日期");
        BTAssert.isTrue(payTime >= 0, "支付日期必须小于等于当前日期");
        BTAssert.isTrue(payTime <= importTime, "支付日期不能小于导入日期");

        BTAssert.notNull(anCustNo, "公司编号不允许为空！");

        final CustMechBase custMechBase = custMechBaseService.findBaseInfo(anCustNo);
        BTAssert.notNull(custMechBase, "没有找到该企业！");

        CommissionPayResult payResult = findByImportDateAndCustNo(anImportDate, anCustNo);
        BTAssert.isNull(payResult, "该企业当日记录已经创建对账记录：企业[" + custMechBase.getCustName() + "] 导入日期[" + anImportDate + "]");

        final boolean auditStatus = commissionFileService.checkFileAuditFinish(anCustNo, anImportDate);

        BTAssert.isTrue(auditStatus, "佣金记录还未审核完毕，请联系企业[" + custMechBase.getCustName() + "]");
        final String[] businStatusArr = new String[] { "0", "1", "2", "3" };
        final boolean createDailyResult = commissionDailyStatementService.findDailyStatementByPayDate(anPayDate,
                anCustNo, businStatusArr);

        BTAssert.isTrue(!createDailyResult, "该企业当日对账记录已经创建");

        final CustOperatorInfo operator = UserUtils.getOperatorInfo();

        payResult = new CommissionPayResult();

        payResult.setOwnCustNo(anCustNo);
        payResult.setOwnCustName(custMechBase.getCustName());
        payResult.setOwnOperOrg(custMechBase.getOperOrg());
        payResult.setImportDate(anImportDate);
        payResult.setPayDate(anPayDate);

        payResult.setBusinStatus(CommissionPayResultStatus.NORMAL);
        payResult.init(operator);

        final int result = this.insert(payResult);

        BTAssert.isTrue(result == 1, "数据保存失败！");

        final int resultCount = commissionPayResultRecordService.saveCreatePayResultRecord(anCustNo,
                custMechBase.getCustName(), custMechBase.getOperOrg(), payResult.getId(), anImportDate, anPayDate);

        calcPayResultRecord(payResult, payResult.getId());

        final int updateResult = this.updateByPrimaryKeySelective(payResult);

        return payResult;
    }

    /**
     *
     * @param anImportDate
     * @param anCustNo
     * @return
     */
    private CommissionPayResult findByImportDateAndCustNo(final String anImportDate, final Long anCustNo) {
        final Map<String, Object> conditionMap = new HashMap<>();

        conditionMap.put("importDate", anImportDate);
        conditionMap.put("ownCustNo", anCustNo);

        return Collections3.getFirst(this.selectByProperty(conditionMap));
    }

    /**
     *
     * @param anId
     * @param anString
     * @return
     */
    private CommissionPayResult findByIdAndCheckStatus(final Long anId, final String anStatus) {
        final CommissionPayResult commissionPayResult = this.selectByPrimaryKey(anId);

        BTAssert.notNull(commissionPayResult, "没有找到账单确认记录！");

        if (BetterStringUtils.isNotBlank(anStatus)) {
            BTAssert.isTrue(BetterStringUtils.equals(anStatus, commissionPayResult.getBusinStatus()), "账单状态不正确！");
        }
        return commissionPayResult;
    }

    // 查询佣金记录
    public Page<CommissionRecord> queryUncheckCommissionRecord(final Long anCustNo, final String anImportDate,
            final int anFlag, final int anPageNum, final int anPageSize) {
        BTAssert.isTrue(UserUtils.platformUser(), "操作失败！");

        BTAssert.notNull(anCustNo, "公司编号不允许为空！");
        BTAssert.isTrue(BetterStringUtils.isNotBlank(anImportDate), "导入日期不允许为空");
        return commissionRecordService.queryRecordListByImportDate(anCustNo, anImportDate, anFlag, anPageNum,
                anPageSize);
    }

    public Map<String, Object> findCountCommissionRecord(final Long anCustNo, final String anImportDate) {
        BTAssert.isTrue(UserUtils.platformUser(), "操作失败！");

        BTAssert.notNull(anCustNo, "公司编号不允许为空！");
        BTAssert.isTrue(BetterStringUtils.isNotBlank(anImportDate), "导入日期不允许为空");
        return commissionRecordService.findRecordListCount(anCustNo, anImportDate);
    }

    // 查询日对账记录 未确认待确认
    public Page<CommissionPayResult> queryNormalPayResultList(Map<String, Object> anMap, final int anFlag,
            final int anPageNum, final int anPageSize) {
        BTAssert.isTrue(UserUtils.platformUser(), "操作失败！");
        // 过滤数据
        anMap = Collections3.filterMapEmptyObject(anMap);
        final Map<String, Object> conditionMap = new HashMap<>();
        if (anMap.get("custNo") != null) {
            conditionMap.put("ownCustNo", anMap.get("custNo").toString());
        }
        if (BetterStringUtils.isNotBlank(anMap.get("GTEpayDate").toString())) {
            conditionMap.put("GTEpayDate", anMap.get("GTEpayDate").toString());
        }
        if (BetterStringUtils.isNotBlank(anMap.get("LTEpayDate").toString())) {
            conditionMap.put("LTEpayDate", anMap.get("LTEpayDate").toString());
        }
        // conditionMap.put("businStatus", CommissionPayResultStatus.NORMAL);
        logger.info("conditionMap:" + conditionMap);
        final Page<CommissionPayResult> pageList = this.selectPropertyByPage(conditionMap, anPageNum, anPageSize,
                anFlag == 1, "ID DESC");
        logger.info("pageList" + pageList);
        logger.info(pageList.getResult().toString());
        return pageList;
    }

    // 查询日对账记录 已确认待审核
    public Page<CommissionPayResult> queryConfirmPayResultList(Map<String, Object> anMap, final int anFlag,
            final int anPageNum, final int anPageSize) {
        BTAssert.isTrue(UserUtils.platformUser(), "操作失败！");
        BTAssert.notNull(anMap, "入参条件为空！");
        BTAssert.notNull(anMap.get("GTEpayDate"), "查询的日期为空！");
        BTAssert.notNull(anMap.get("LTEpayDate"), "查询的日期的长度为空！");
        // anMap.put("businStatus", new String[] { CommissionPayResultStatus.CONFIRM, CommissionPayResultStatus.AUDIT
        // });
        return this.selectPropertyByPage(anMap, anPageNum, anPageSize, anFlag == 1, "ID desc");
    }

    // 查询日对账记录 已审核
    public Page<CommissionPayResult> queryAuditPayResultList(final Long anCustNo, final String anPayDate,
            final int anFlag, final int anPageNum, final int anPageSize) {
        BTAssert.isTrue(UserUtils.platformUser(), "操作失败！");

        final Map<String, Object> conditionMap = new HashMap<>();
        if (anCustNo != null) {
            conditionMap.put("ownCustNo", anCustNo);
        }
        if (StringUtils.isNotBlank(anPayDate)) {
            conditionMap.put("payDate", anPayDate);
        }
        conditionMap.put("businStatus", CommissionPayResultStatus.AUDIT);

        return this.selectPropertyByPage(conditionMap, anPageNum, anPageSize, anFlag == 1);
    }

    // 未对账记录列表
    public Page<CommissionPayResultRecord> queryAllPayResultRecords(final Long anPayResultId, final int anFlag,
            final int anPageNum, final int anPageSize) {
        BTAssert.isTrue(UserUtils.platformUser(), "不是平台用户，操作失败！");

        findByIdAndCheckStatus(anPayResultId, null);

        return commissionPayResultRecordService.queryAllPayResultRecords(anPayResultId, anFlag, anPageNum, anPageSize);
    }

    // 未对账记录列表
    public Page<CommissionPayResultRecord> queryUncheckPayResultRecords(final Map<String, Object> anParam,
            final Long anPayResultId, final int anFlag, final int anPageNum, final int anPageSize) {
        BTAssert.isTrue(UserUtils.platformUser(), "操作失败！");

        findByIdAndCheckStatus(anPayResultId, null);

        return commissionPayResultRecordService.queryUncheckPayResultRecords(anParam, anPayResultId, anFlag, anPageNum,
                anPageSize);
    }

    // 成功列表
    public Page<CommissionPayResultRecord> querySuccessPayResultRecords(final Long anPayResultId, final int anFlag,
            final int anPageNum, final int anPageSize) {
        BTAssert.isTrue(UserUtils.platformUser(), "操作失败！");

        findByIdAndCheckStatus(anPayResultId, null);

        return commissionPayResultRecordService.querySuccessPayResultRecords(anPayResultId, anFlag, anPageNum,
                anPageSize);
    }

    // 失败列表
    public Page<CommissionPayResultRecord> queryFailurePayResultRecords(final Long anPayResultId, final int anFlag,
            final int anPageNum, final int anPageSize) {
        BTAssert.isTrue(UserUtils.platformUser(), "操作失败！");

        findByIdAndCheckStatus(anPayResultId, null);

        return commissionPayResultRecordService.queryFailurePayResultRecords(anPayResultId, anFlag, anPageNum,
                anPageSize);
    }

    // 批量确认成功
    public Map<String, Object> saveConfirmSuccessPayResultRecords(final Long anPayResultId,
            final List<Long> anPayResultRecords) {
        BTAssert.isTrue(UserUtils.platformUser(), "操作失败！");

        final CommissionPayResult payResult = findByIdAndCheckStatus(anPayResultId, CommissionPayResultStatus.NORMAL);

        final Map<String, Object> resultMap = commissionPayResultRecordService
                .saveConfirmSuccessPayResultRecords(anPayResultId, anPayResultRecords);

        calcPayResultRecord(payResult, payResult.getId());

        final int result = this.updateByPrimaryKeySelective(payResult);

        return resultMap;
    }

    // 批量确认失败
    public Map<String, Object> saveConfirmFailurePayResultRecords(final Long anPayResultId,
            final List<Long> anPayResultRecords) {
        BTAssert.isTrue(UserUtils.platformUser(), "操作失败！");

        final CommissionPayResult payResult = findByIdAndCheckStatus(anPayResultId, CommissionPayResultStatus.NORMAL);

        final Map<String, Object> resultMap = commissionPayResultRecordService
                .saveConfirmFailurePayResultRecords(anPayResultId, anPayResultRecords);

        calcPayResultRecord(payResult, payResult.getId());

        final int result = this.updateByPrimaryKeySelective(payResult);

        return resultMap;
    }

    // 成功变失败
    public CommissionPayResultRecord saveSuccessToFailurePayResultRecord(final Long anPayResultId,
            final Long anPayResultRecordId) {
        BTAssert.isTrue(UserUtils.platformUser(), "操作失败！");

        final CommissionPayResult payResult = findByIdAndCheckStatus(anPayResultId, CommissionPayResultStatus.NORMAL);

        final CommissionPayResultRecord payResultRecord = commissionPayResultRecordService
                .saveSuccessToFailurePayResultRecord(anPayResultId, anPayResultRecordId);

        calcPayResultRecord(payResult, payResult.getId());

        final int result = this.updateByPrimaryKeySelective(payResult);

        return payResultRecord;
    }

    // 失败变成功
    public CommissionPayResultRecord saveFailureToSuccessPayResultRecord(final Long anPayResultId,
            final Long anPayResultRecordId) {
        BTAssert.isTrue(UserUtils.platformUser(), "操作失败！");

        final CommissionPayResult payResult = findByIdAndCheckStatus(anPayResultId, CommissionPayResultStatus.NORMAL);

        final CommissionPayResultRecord payResultRecord = commissionPayResultRecordService
                .saveFailureToSuccessPayResultRecord(anPayResultId, anPayResultRecordId);

        calcPayResultRecord(payResult, payResult.getId());

        final int result = this.updateByPrimaryKeySelective(payResult);

        return payResultRecord;
    }

    // 确认日对账单
    public CalcPayResult saveConfirmPayResult(final Long anPayResultId) {
        BTAssert.isTrue(UserUtils.platformUser(), "操作失败！");

        final CommissionPayResult payResult = findByIdAndCheckStatus(anPayResultId, CommissionPayResultStatus.NORMAL);

        commissionPayResultRecordService.checkConfirmStatus(anPayResultId);

        payResult.setBusinStatus(CommissionPayResultStatus.CONFIRM);

        calcPayResultRecord(payResult, anPayResultId);

        final int result = this.updateByPrimaryKeySelective(payResult);

        BTAssert.isTrue(result == 1,
                "确认日对账单失败，公司[" + payResult.getCustName() + "] 导入日期[" + payResult.getImportDate() + "]");

        return commissionPayResultRecordService.calcPayResultRecord(anPayResultId);
    }

    private void calcPayResultRecord(final CommissionPayResult payResult, final Long anPayResultId) {
        final CalcPayResult calcResult = commissionPayResultRecordService.calcPayResultRecord(anPayResultId);
        final Long totalAmount = calcResult.getTotalAmount();
        final BigDecimal totalBalance = calcResult.getTotalBalance();
        final Long paySuccessAmount = calcResult.getPaySuccessAmount();
        final BigDecimal paySuccessBalance = calcResult.getPaySuccessBalance();
        final Long payFailureAmount = calcResult.getPayFailureAmount();
        final BigDecimal payFailureBalance = calcResult.getPayFailureBalance();

        payResult.setTotalAmount(totalAmount);
        payResult.setTotalBalance(totalBalance);
        payResult.setPayTotalAmount(totalAmount);
        payResult.setPayTotalBalance(totalBalance);
        payResult.setPaySuccessAmount(paySuccessAmount);
        payResult.setPaySuccessBalance(paySuccessBalance);
        payResult.setPayFailureAmount(payFailureAmount);
        payResult.setPayFailureBalance(payFailureBalance);
    }

    // 审核日对账单
    public CalcPayResult saveAuditPayResult(final Long anPayResultId) {
        BTAssert.isTrue(UserUtils.platformUser(), "操作失败！");

        final CommissionPayResult payResult = findByIdAndCheckStatus(anPayResultId, CommissionPayResultStatus.CONFIRM);
        /*if (payResult.getPayFailureAmount() != 0) {
            BTAssert.notNull(null, "付款结果存在不成功的记录，审核失败！");
        }*/
        payResult.setBusinStatus(CommissionPayResultStatus.AUDIT);

        final CustOperatorInfo operator = UserUtils.getOperatorInfo();

        payResult.modify(operator);

        final int result = this.updateByPrimaryKeySelective(payResult);

        //

        BTAssert.isTrue(result == 1,
                "确认日对账单失败，公司[" + payResult.getCustName() + "] 导入日期[" + payResult.getImportDate() + "]");

        // TODO 回写导入记录
        commissionPayResultRecordService.saveWritebackRecordStatus(anPayResultId);
        // 回写上传文件记录
        commissionPayResultRecordService.saveCommissionFileBusinStatus(BetterDateUtils.getNumDate(),
                CommissionPayResultStatus.FILE_TYPE);
        return commissionPayResultRecordService.calcPayResultRecord(anPayResultId);
    }

    // 删除日对账单
    public int SaveDeletePayResult(final Long anPayResultId) {
        BTAssert.isTrue(UserUtils.platformUser(), "操作失败！");
        BTAssert.notNull(anPayResultId, "删除条件为空，删除失败！");

        // 回删佣金支付记录结果
        final CommissionPayResultRecord payResultRecord = new CommissionPayResultRecord();
        payResultRecord.setPayResultId(anPayResultId);
        commissionPayResultRecordService.delete(payResultRecord);
        // 删除上传文件记录
        final CommissionFile commissionFile = new CommissionFile();
        commissionFile.setImportDate(BetterDateUtils.getNumDate());
        commissionFile.setFileType(CommissionPayResultStatus.AUDIT);
        commissionFileService.delete(commissionFile);
        // 删除日账单结果
        final CommissionPayResult commissionRecoed = new CommissionPayResult();
        commissionRecoed.setId(anPayResultId);

        return this.delete(commissionRecoed);
    }

    /**
     * @param anPayResultId
     * @return
     */
    public Map<String, Object> findCountPayResultRecord(final Long anPayResultId) {
        BTAssert.isTrue(UserUtils.platformUser(), "操作失败！");
        final CommissionPayResult payResult = findByIdAndCheckStatus(anPayResultId, null);

        final Map<String, Object> result = new HashMap<>();
        final CalcPayResult calcPayResult = commissionPayResultRecordService.calcPayResultRecord(anPayResultId);
        result.put("payResult", payResult);
        result.put("calcPayResult", calcPayResult);

        return result;
    }

    /**
     * @param anRefNo
     * @return
     */
    public Map<String, Object> findCommissionRecord(final String anRefNo) {
        final CommissionRecord record = commissionRecordService.findRecord(anRefNo);
        final CommissionPayResultRecord payResultRecord = commissionPayResultRecordService.findPayResultRecord(anRefNo);

        final Map<String, Object> commissionRecord = new HashMap<>();
        commissionRecord.put("record", record);
        commissionRecord.put("payResultRecord", payResultRecord);

        return commissionRecord;
    }

    /**
     * 
     * @Title: systemAcountBill 
     * @Description: TODO(支付结果对账) 
     * @param @param anPayResultId
     * @param @return 参数说明 
     * @return Map<String,Object> 返回类型 
     * @throws 
     * @author chenlq
     * @date 2017年11月15日 上午9:58:58
     */
    public CommissionPayResult systemAcountBill(final Long anPayResultId) {
        BTAssert.notNull(anPayResultId, "条件为空！");
        final Map<String, Object> findCondition = new HashMap<String, Object>();
        findCondition.put("payResultId", anPayResultId);
        final List<CommissionPayResultRecord> payResultRecords = commissionPayResultRecordService
                .selectByProperty(findCondition);
        final CommissionPayResult queryPayResult = this.selectByPrimaryKey(anPayResultId);
        if (queryPayResult.getTotalAmount() != queryPayResult.getPayTotalAmount()) {
            BTAssert.notNull(null, "佣金对账失败，支付的佣金与原始导入的佣金数目不一致，请手动调账！");
        }
        if (queryPayResult.getTotalAmount() != queryPayResult.getPaySuccessAmount()) {
            BTAssert.notNull(null, "佣金对账失败，支付成功的佣金与原始导入的佣金数目不一致，请手动调账！");
        }
        if (queryPayResult.getTotalBalance().compareTo(queryPayResult.getPayTotalBalance()) != 0) {
            BTAssert.notNull(null, "佣金对账失败，支付的佣金数额与原始导入的数额不一致，请手动调账！");
        }
        if (queryPayResult.getTotalBalance().compareTo(queryPayResult.getPaySuccessBalance()) != 0) {
            BTAssert.notNull(null, "佣金对账失败，支付成功的佣金数额与原始导入的数额不一致，请手动调账！");
        }
        if (queryPayResult.getPayFailureAmount() != 0) {
            BTAssert.notNull(null, "佣金对账失败，存在支付不成功的佣金，请手动调账！");
        }
        if (queryPayResult.getPayFailureBalance().compareTo(new BigDecimal(0.00)) != 0) {
            BTAssert.notNull(null, "佣金对账失败，存在支付不成功的佣金，请手动调账！");
        }
        Long downFileId = 0l;
        try {
            int row = 0;

            for (final CommissionPayResultRecord payResultRecord : payResultRecords) {
                row++;
                // 根据凭证记录查找原始记录
                final CommissionRecord commissionRecord = commissionRecordService
                        .findRecord(payResultRecord.getRefNo());
                if (commissionRecord == null) {
                    BTAssert.notNull(null,
                            "第" + row + "行记录的原始佣金数据记录中没有这条数据,凭证号为" + payResultRecord.getRefNo() + ",请查证！");
                }
                if (!payResultRecord.getPayTargetBankAccount().equals(commissionRecord.getBankAccount())) {
                    BTAssert.notNull(null,
                            "第" + row + "行记录的银行账号与佣金记录中银行帐号不一致，凭证号为" + payResultRecord.getRefNo() + ",请查证！");
                }
                if (!payResultRecord.getPayTargetBankAccountName().equals(commissionRecord.getBankAccountName())) {

                    BTAssert.notNull(null, "第" + row + "行记录的银行帐号用户名不一致，凭证号为" + payResultRecord.getRefNo() + ",请查证！");
                }
                if (!payResultRecord.getPayBalance().equals(commissionRecord.getBalance())) {

                    BTAssert.notNull(null, "第" + row + "行记录的佣金支付金额不一致,凭证号为" + payResultRecord.getRefNo() + ",请核实！");
                }
                downFileId = commissionRecord.getFileDownId();
            }
        }
        catch (final Exception e) {
            // 回写支付结果记录对账失败的状态值
            final CommissionPayResultRecord setPayResultAccountStatus = new CommissionPayResultRecord();
            setPayResultAccountStatus.setAccountBalanceStatus(CommissionPayResultStatus.AUDIT);
            commissionPayResultRecordService.updateByExampleSelective(setPayResultAccountStatus, findCondition);

            // 回写支付结果对账失败的状态值
            final Map<String, Object> condition = new HashMap<String, Object>();
            condition.put("id", anPayResultId);
            final CommissionPayResult payResult = findByIdAndCheckStatus(anPayResultId, null);
            payResult.setAccountBalanceStatus(CommissionPayResultStatus.AUDIT);
            this.updateByExampleSelective(payResult, condition);
            BTAssert.notNull(null, e.getMessage());
        }

        // 回写支付结果记录对账成功的状态值
        final CommissionPayResultRecord setPayResultAccountStatus = new CommissionPayResultRecord();
        setPayResultAccountStatus.setAccountBalanceStatus(CommissionPayResultStatus.CONFIRM);
        // 记录当前对账的时间
        setPayResultAccountStatus.setCompareBillDate(BetterDateUtils.getNumDate());
        setPayResultAccountStatus.setCompareBillTime(BetterDateUtils.getNumTime());
        commissionPayResultRecordService.updateByExampleSelective(setPayResultAccountStatus, findCondition);

        // 回写支付结果对账成功的状态值
        final Map<String, Object> condition = new HashMap<String, Object>();
        condition.put("id", anPayResultId);
        final CommissionPayResult payResult = findByIdAndCheckStatus(anPayResultId, null);
        payResult.setAccountBalanceStatus(CommissionPayResultStatus.CONFIRM);
        // 记录当前对帐的时间
        payResult.setCompareBillDate(BetterDateUtils.getNumDate());
        payResult.setCompareBillTime(BetterDateUtils.getNumTime());
        this.updateByExampleSelective(payResult, condition);

        // 回写佣金下载文件记录
        final CommissionFileDown fileDown = commissionFileDownService.selectByPrimaryKey(downFileId);
        fileDown.setConfirmStatus(CommissionPayResultStatus.DAILY_ACCOUNT);
        commissionFileDownService.updateByPrimaryKeySelective(fileDown);
        return payResult;
    }

    /**
     * 
     * @Title: saveHandAcountBill 
     * @Description: TODO(佣金数据手动对账确认) 
     * @param @param anMap
     * @param @return 参数说明 
     * @return CommissionPayResult 返回类型 
     * @throws 
     * @author chenlq
     * @date 2017年11月17日 上午11:44:33
     */
    public CommissionPayResult saveHandAcountBill(Map<String, Object> anMap) {
        BTAssert.isTrue(UserUtils.platformUser(), "操作失败，不是平台用户！");
        BTAssert.notNull(anMap, "条件为空！");
        final Map<String, Object> findCondition = new HashMap<String, Object>();
        findCondition.put("payResultId", anMap.get("payResultId"));
        final List<CommissionPayResultRecord> payResultRecords = commissionPayResultRecordService
                .selectByProperty(findCondition);
        Long payTotalAmount = 0l;
        BigDecimal payTotalBlance = new BigDecimal(0);
        Long paySuccessAmount = 0l;
        BigDecimal paySuccessBlance = new BigDecimal(0);
        Long payFailAmount = 0l;
        BigDecimal payFailBlance = new BigDecimal(0);
        for (final CommissionPayResultRecord payResultRecord : payResultRecords) {
            if (!CommissionPayResultStatus.AUDIT.equals(payResultRecord.getBusinStatus())) {
                BTAssert.notNull(null, "存在未审核的数据，请审核后再试！");
            }
            if (CommissionPayResultStatus.CONFIRM.equals(payResultRecord.getPayResult())) {
                paySuccessAmount++;
                paySuccessBlance = MathExtend.add(paySuccessBlance, payResultRecord.getPayBalance());
            }
            if (CommissionPayResultStatus.AUDIT.equals(payResultRecord.getPayResult())) {
                BTAssert.notNull(null, "请处理完支付不成功的佣金再来手工对账！");
                payFailAmount++;
                payFailBlance = MathExtend.add(payFailBlance, payResultRecord.getPayBalance());
            }
        }
        payTotalAmount = paySuccessAmount + payFailAmount;
        payTotalBlance = MathExtend.add(paySuccessBlance, payFailBlance);

        final CommissionPayResult setPayResultCondition = new CommissionPayResult();
        setPayResultCondition.modify(UserUtils.getOperatorInfo());
        setPayResultCondition.setId(Long.parseLong(anMap.get("payResultId").toString()));
        setPayResultCondition.setPaySuccessAmount(paySuccessAmount);
        setPayResultCondition.setPaySuccessBalance(paySuccessBlance);
        setPayResultCondition.setPayFailureAmount(payFailAmount);
        setPayResultCondition.setPayFailureBalance(payFailBlance);
        setPayResultCondition.setPayTotalAmount(payTotalAmount);
        setPayResultCondition.setPayTotalBalance(payTotalBlance);
        // 记录当前对帐的时间
        setPayResultCondition.setCompareBillDate(BetterDateUtils.getNumDate());
        setPayResultCondition.setCompareBillTime(BetterDateUtils.getNumTime());
        setPayResultCondition.setAccountBalanceStatus(CommissionPayResultStatus.CONFIRM);
        if (anMap.get("remarkDescription") != null) {
            setPayResultCondition.setRemarkDescription(anMap.get("remarkDescription").toString());
        }
        this.updateByPrimaryKeySelective(setPayResultCondition);

        // 回写支付结果记录对账成功的状态值
        final CommissionPayResultRecord setPayResultAccountStatus = new CommissionPayResultRecord();
        setPayResultAccountStatus.setAccountBalanceStatus(CommissionPayResultStatus.CONFIRM);
        // 记录当前对账的时间
        setPayResultAccountStatus.setCompareBillDate(BetterDateUtils.getNumDate());
        setPayResultAccountStatus.setCompareBillTime(BetterDateUtils.getNumTime());

        commissionPayResultRecordService.updateByExampleSelective(setPayResultAccountStatus, findCondition);
        try {

            systemAcountBill(Long.parseLong(anMap.get("payResultId").toString()));
        }
        catch (final Exception e) {
            BTAssert.notNull(null, e.getMessage());
        }
        // 返回结果
        final CommissionPayResult payResultCondition = this.selectOne(setPayResultCondition);
        return payResultCondition;

    }

    /**
     * 
     * @Title: queryCompareBill 
     * @Description: TODO(查询出对帐信息) 
     * @param @param anMap
     * @param @return 参数说明 
     * @return Map<String,Object> 返回类型 
     * @throws 
     * @author chenlq
     * @date 2017年11月16日 下午3:10:40
     */
    public Map<String, Object> queryCompareBill(Map<String, Object> anMap) {
        BTAssert.notNull(anMap, "条件为空！");
        BTAssert.notNull(anMap.get("GTEimportDate"), "导入日期条件为空！");
        BTAssert.notNull(anMap.get("payDate"), "支付日期条件为空！");
        final Map<String, Object> findCondition = new HashMap<String, Object>();
        findCondition.put("importDate", anMap.get("GTEimportDate"));
        findCondition.put("confirmStatus", CommissionPayResultStatus.AUDIT);
        // 查询到导入的佣金数据
        final List<CommissionRecord> exportRecords = commissionRecordService.selectByProperty(findCondition);
        BTAssert.notNull(exportRecords, "没有查到导入的佣金记录，或佣金记录不存在！");
        logger.info("查询导入的佣金数据,入参：" + exportRecords);

        // 查寻支付结果的佣金数据
        findCondition.clear();
        findCondition.put("payDate", anMap.get("payDate"));
        final List<CommissionPayResultRecord> payResultRecords = commissionPayResultRecordService
                .selectByProperty(findCondition);
        BTAssert.notNull(payResultRecords, "没有查到支付的佣金记录，或佣金记录不存在！");
        logger.info("查询导入的佣金数据,入参：" + payResultRecords);

        // 查询佣金结果记录
        final CommissionPayResult commissionPayResult = commissionPayResultService
                .selectByPrimaryKey(payResultRecords.get(0).getPayResultId());

        // 返回结果集
        final Map<String, Object> results = new HashMap<String, Object>();
        results.put("exportRecords", exportRecords);
        results.put("payResultRecords", payResultRecords);
        results.put("commissionPayResult", commissionPayResult);
        return results;
    }

    /**
     * 
     * @Title: saveHandCompareBillInfo 
     * @Description: TODO(保存对帐的结果) 
     * @param @param anMap
     * @param @return 参数说明 
     * @return CommissionRecord 返回类型 
     * @throws 
     * @author chenlq
     * @date 2017年11月16日 下午3:37:58
     */
    public CommissionRecord saveHandCompareBillInfo(Map<String, Object> anMap) {
        BTAssert.notNull(anMap, "条件为空！");
        BTAssert.notNull(anMap.get("refNo"), "查询的编号条件为空！");
        // 更新对账信息
        final Map<String, Object> queryCondition = new HashMap<String, Object>();
        queryCondition.put("refNo", anMap.get("refNo"));
        // 判断支付结果记录的数据是否存在，不存在插入
        final CommissionPayResultRecord payResultRecord = new CommissionPayResultRecord();
        payResultRecord.setRefNo(anMap.get("refNo").toString());
        final CommissionPayResultRecord findPayResult = commissionPayResultRecordService.selectOne(payResultRecord);
        if (findPayResult == null) {
            final CommissionRecord commissionRecord = new CommissionRecord();
            commissionRecord.setRefNo(anMap.get("refNo").toString());
            final CommissionRecord findResult = commissionRecordService.selectOne(commissionRecord);
            payResultRecord.init(UserUtils.getOperatorInfo());
            payResultRecord.setId(findResult.getId());
            payResultRecord.setPayResultId(Long.parseLong(anMap.get("payResultId").toString()));
            payResultRecord.setRecordId(findResult.getId());
            payResultRecord.setRecordRefNo(findResult.getRefNo());
            payResultRecord.setPayResultOrderNo("平台手动录入");
            payResultRecord.setImportDate(findResult.getImportDate());
            payResultRecord.setImportTime(findResult.getImportTime());
            payResultRecord.setPayDate(BetterDateUtils.getNumDate());
            payResultRecord.setPayTime(BetterDateUtils.getNumTime());
            payResultRecord.setPayBalance(findResult.getBalance());
            payResultRecord.setPayTargetBank(findResult.getBank());
            payResultRecord.setPayTargetBankName(findResult.getBankName());;
            payResultRecord.setPayTargetBankAccount(findResult.getBankAccount());
            payResultRecord.setPayTargetBankAccountName(findResult.getBankAccountName());
            payResultRecord.setPayBankCode(findResult.getBankPayCode());
            payResultRecord.setPayTargetMobileNo(findResult.getContactsMobileNo());
            payResultRecord.setPayBankAccountType("个人账户");
            payResultRecord.setPayResult(CommissionPayResultStatus.CONFIRM);
            payResultRecord.setBusinStatus(CommissionPayResultStatus.CONFIRM);
            payResultRecord.setCustNo(findResult.getCustNo());
            payResultRecord.setCustName(findResult.getCustName());
            payResultRecord.setOperOrg(findResult.getOperOrg());
            payResultRecord.setBusinStatus(CommissionPayResultStatus.AUDIT);
            payResultRecord.setDescription("平台添加");
            commissionPayResultRecordService.insert(payResultRecord);
        } else {
            final CommissionRecord commissionRecord = new CommissionRecord();
            commissionRecord.setRefNo(anMap.get("refNo").toString());
            final CommissionRecord findResult = commissionRecordService.selectOne(commissionRecord);
            findPayResult.setPayTargetBankAccountName(findResult.getBankAccountName());
            findPayResult.setPayBankAccount(findResult.getBankAccount());
            findPayResult.setPayBalance(findResult.getBalance());
            findPayResult.setPayBankCode(findResult.getBankPayCode());
            findPayResult.setPayResult(anMap.get("payStatus").toString());
            findPayResult.setPayResultPurpose(anMap.get("payPurpose").toString());
            findPayResult.setPayDealResult(anMap.get("dealResult").toString());
            commissionPayResultRecordService.updateByPrimaryKey(findPayResult);
        }

        // 更改佣金导入的信息
        final CommissionRecord commissionRecord = new CommissionRecord();
        // 更新佣金支付结果记录信息
        // final CommissionPayResultRecord payResultRecord = new CommissionPayResultRecord();

        if (anMap.get("payStatus") != null) {
            commissionRecord.setPayStatus(anMap.get("payStatus").toString());
            payResultRecord.setPayResult(anMap.get("payStatus").toString());
        }

        if (anMap.get("payPurpose") != null) {
            commissionRecord.setPayPurpose(anMap.get("payPurpose").toString());
            payResultRecord.setPayResultPurpose(anMap.get("payPurpose").toString());
        }

        if (anMap.get("dealResult") != null) {
            commissionRecord.setDealResult(anMap.get("dealResult").toString());
            payResultRecord.setPayDealResult(anMap.get("dealResult").toString());
        }
        logger.info("更新信息：" + commissionRecord);
        logger.info("更新信息：" + payResultRecord);
        commissionRecordService.updateByExampleSelective(commissionRecord, queryCondition);
        commissionPayResultRecordService.updateByExampleSelective(payResultRecord, queryCondition);
        backWritePayResult(Long.parseLong(anMap.get("payResultId").toString()));
        return commissionRecord;
    }

    /**
     * 
     * @Title: backWritePayResult 
     * @Description: TODO(回写调整后的状态) 
     * @param @param payResultId 参数说明 
     * @return void 返回类型 
     * @throws 
     * @author chenlq
     * @date 2017年12月15日 上午11:25:17
     */
    public void backWritePayResult(Long payResultId) {
        final CommissionPayResult payResult = new CommissionPayResult();
        // 根据支付日期查询出支付结果记录数据
        final Map<String, Object> map = new HashMap<String, Object>();
        map.put("payResultId", payResultId);
        final List<CommissionPayResultRecord> payResults = commissionPayResultRecordService.selectByProperty(map);
        BigDecimal payTotalBalance = new BigDecimal(0);
        BigDecimal paySuccessBalance = new BigDecimal(0);
        BigDecimal payFailBalance = new BigDecimal(0);
        Long payTotalAmount = 0l;
        Long paySuccessAmount = 0l;
        Long payFailAmount = 0l;
        // 计算出佣金的总额，支付成功的总额，支付失败的总额
        for (final CommissionPayResultRecord singleRecord : payResults) {
            payTotalAmount++;
            payTotalBalance = MathExtend.add(payTotalBalance, singleRecord.getPayBalance());
            if ("1".equals(singleRecord.getPayResult())) {
                paySuccessBalance = MathExtend.add(paySuccessBalance, singleRecord.getPayBalance());
                paySuccessAmount++;
            }
            if ("2".equals(singleRecord.getPayResult())) {
                payFailBalance = MathExtend.add(payFailBalance, singleRecord.getPayBalance());
                payFailAmount++;
            }
        }
        payResult.setPayTotalBalance(payTotalBalance);
        payResult.setPayTotalAmount(payTotalAmount);
        payResult.setPaySuccessAmount(paySuccessAmount);
        payResult.setPaySuccessBalance(paySuccessBalance);
        payResult.setPayFailureAmount(payFailAmount);
        payResult.setPayFailureBalance(payFailBalance);
        payResult.setId(payResultId);
        commissionPayResultService.updateByPrimaryKeySelective(payResult);
    }

    /**
     * 
     * @Title: queryUploadFileLisInfo 
     * @Description: TODO(查询出文件的总和) 
     * @param @return 参数说明 
     * @return List<CommissionFile> 返回类型 
     * @throws 
     * @author chenlq
     * @date 2017年12月15日 下午3:34:49
     */
    public List<CommissionFile> queryUploadFileLisInfo(String importDate) {
        final Map<String, Object> conditionMap = new HashMap<String, Object>();
        conditionMap.put("importDate", importDate);
        conditionMap.put("fileType", CommissionPayResultStatus.AUDIT);
        return commissionFileService.selectByProperty(conditionMap);
    }
}
